<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="iOS," />





  <link rel="alternate" href="/atom.xml" title="Bingo's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="笔记分类中定义的属性名最好添加一个前缀Masonry : mas_xxx 123[label mas_makeConstraints:^(MASConstraintMaker *make) &amp;#123;    make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(20, 20, 20, 20));&amp;#125;]; SDWebImage : sd">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS战斗总结笔记一期">
<meta property="og:url" content="https://bingozb.github.io/3.html">
<meta property="og:site_name" content="Bingo's Blog">
<meta property="og:description" content="笔记分类中定义的属性名最好添加一个前缀Masonry : mas_xxx 123[label mas_makeConstraints:^(MASConstraintMaker *make) &amp;#123;    make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(20, 20, 20, 20));&amp;#125;]; SDWebImage : sd">
<meta property="og:updated_time" content="2017-09-04T19:06:15.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS战斗总结笔记一期">
<meta name="twitter:description" content="笔记分类中定义的属性名最好添加一个前缀Masonry : mas_xxx 123[label mas_makeConstraints:^(MASConstraintMaker *make) &amp;#123;    make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(20, 20, 20, 20));&amp;#125;]; SDWebImage : sd">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: 'JE30EVH7NI',
      apiKey: '862bb3deb9a3166ed99de0be6527f59c',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于「 ${query} 」的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://bingozb.github.io/3.html"/>





  <title>iOS战斗总结笔记一期 | Bingo's Blog</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c8a59b9753bce3ec58f81c89e2acce96";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bingo's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry, Stay Foolish.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://bingozb.github.io/3.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bingo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bingo's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                iOS战斗总结笔记一期
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-08-10T10:15:19+08:00">
                2016-08-10
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/战斗笔记/" itemprop="url" rel="index">
                    <span itemprop="name">战斗笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/3.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="3.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/3.html" class="leancloud_visitors" data-flag-title="iOS战斗总结笔记一期">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="笔记"><a href="#笔记" class="headerlink" title="笔记"></a>笔记</h2><h3 id="分类中定义的属性名最好添加一个前缀"><a href="#分类中定义的属性名最好添加一个前缀" class="headerlink" title="分类中定义的属性名最好添加一个前缀"></a>分类中定义的属性名最好添加一个前缀</h3><p>Masonry : mas_xxx</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">[label mas_makeConstraints:^(MASConstraintMaker *make) &#123;</div><div class="line">    make.edges.equalTo(<span class="keyword">self</span>.view).insets(<span class="built_in">UIEdgeInsetsMake</span>(<span class="number">20</span>, <span class="number">20</span>, <span class="number">20</span>, <span class="number">20</span>));</div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<p>SDWebImage : sd_xxx</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">[<span class="keyword">self</span>.headImgView sd_setImageWithURL:[<span class="built_in">NSURL</span> URLWithString:DKImgUrl(joinRecord.uphoto)]];</div></pre></td></tr></table></figure>
<p>比如我们通常写的view的扩展分类，会定义一些<code>x</code>、<code>y</code>、<code>width</code>、<code>height</code>等属性，如果不写上前缀，有可能跟苹果原有的一些属性同名导致冲突，还可能跟其他框架定义的属性同名冲突，比如<code>Masonry</code>里就有<code>width</code>、<code>height</code>等属性名;</p>
<a id="more"></a>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">[label mas_makeConstraints:^(MASConstraintMaker *make) &#123;</div><div class="line">    make.center.equalTo(<span class="keyword">self</span>.view);</div><div class="line">    make.height.equalTo(@<span class="number">50</span>);</div><div class="line">    make.width.equalTo(@<span class="number">50</span>);</div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<p>正确姿势:</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">x &gt;&gt;&gt; dk_x</div><div class="line">y &gt;&gt;&gt; dk_y</div><div class="line">width &gt;&gt;&gt; dk_width</div><div class="line">height &gt;&gt;&gt; dk_height</div><div class="line">...</div></pre></td></tr></table></figure>
<h3 id="导航栏标题"><a href="#导航栏标题" class="headerlink" title="导航栏标题"></a>导航栏标题</h3><p>设置导航栏标题应该用 self.navigationItem.title，而不是用 self.title，self.title 是许多操作的结合体操作，除了更改控制器导航栏标题，还会改了底部 tabBarItem 的标题，甚至还可能使 tabBar 里边的 item 的排列顺序发生变化。</p>
<h3 id="宏"><a href="#宏" class="headerlink" title="宏"></a>宏</h3><ul>
<li>定义宏的时候不能是纯小写字母，苹果的做法是全部大写。</li>
<li>定义的宏如果找不到（按Command+鼠标左键出现一个?），可能是定义在了 Build Setting 中，比如 DEBUG 这个宏。</li>
</ul>
<h3 id="Nib文字换行"><a href="#Nib文字换行" class="headerlink" title="Nib文字换行"></a>Nib文字换行</h3><ul>
<li>在xib或者storyboard中,UILabel、UITextView等控件的文字换行，需要设置Lines为0，然后按 option + 回车 即可换行。</li>
<li>在代码中可以用<code>\n</code>来换行</li>
</ul>
<h3 id="AutoLayout"><a href="#AutoLayout" class="headerlink" title="AutoLayout"></a>AutoLayout</h3><p>在xib或者storyboard中做约束时，如果要距离顶部或者底部约束，参照的目标不应该选layout Guide，而要选UIView，否则会出现许多奇怪的问题。</p>
<h3 id="IBOutlet"><a href="#IBOutlet" class="headerlink" title="IBOutlet"></a>IBOutlet</h3><p>同一个xib中，如果有两个或者多个view，它们的内容几乎一致（只有小部分有差异），那么对于相同的控件可以共用一个暴露在代码中的 IBOutlet，不需要每个控件都拉一条线给一个独有的 IBOutlet。</p>
<h3 id="weak-amp-strong"><a href="#weak-amp-strong" class="headerlink" title="weak &amp; strong"></a>weak &amp; strong</h3><p>在写 property 的时候，一般控件的策略是weak，但需要懒加载的控件要用strong。</p>
<h3 id="dispatch-async"><a href="#dispatch-async" class="headerlink" title="dispatch_async"></a>dispatch_async</h3><p>如果在 tableView 或者 collectionView 的 reloadData 方法后需要立即获取 cell、高度，或者需要做滚动等操作，那么直接在 reloadData 后执行代码是有可能出问题的。reloadData 并不会等待 tableview 更新结束后才返回，而是立即返回，然后去计算cell高度，获取cell等。</p>
<p>如果表格中的数据非常大，在一个 run loop 周期还没执行完，这时需要 tableview 视图数据的操作就会出问题了。apple并没有直接提供 reloadData 的api，想要程序延迟到 reloadData 结束再操作，可以用以下两种方法:</p>
<h4 id="方法一"><a href="#方法一" class="headerlink" title="方法一"></a>方法一</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">[<span class="keyword">self</span>.tableView reloadData];</div><div class="line">[<span class="keyword">self</span>.tableView layoutIfNeeded];</div><div class="line"><span class="comment">// 刷新完成</span></div></pre></td></tr></table></figure>
<h4 id="方法二"><a href="#方法二" class="headerlink" title="方法二"></a>方法二</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">[<span class="keyword">self</span>.tableView reloadData];</div><div class="line"><span class="built_in">dispatch_async</span>(dispatch_get_main_queue(), ^&#123;</div><div class="line">    <span class="comment">// 刷新完成</span></div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>reloadData 会在主队列执行，而 dispatch_get_main_queue 会等待机会，直到主队列空闲才执行。<br></p>
<p>错误姿势: 把 reloadData 放在 dispatch_async(dispatch_get_main_queue(), ^{}); 里面！</p>
<h3 id="UICollectionView加载不到xib"><a href="#UICollectionView加载不到xib" class="headerlink" title="UICollectionView加载不到xib"></a>UICollectionView加载不到xib</h3><p>UICollectionView与UITableView不同，需要在.m文件中重写 initWithFrame 方法，再次加载nib。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">instancetype</span>)initWithFrame:(<span class="built_in">CGRect</span>)frame</div><div class="line">&#123;</div><div class="line">    <span class="keyword">if</span> (<span class="keyword">self</span> = [<span class="keyword">super</span> initWithFrame:frame]) &#123;</div><div class="line">        <span class="keyword">self</span> = [[[<span class="built_in">NSBundle</span> mainBundle] loadNibNamed:<span class="string">@"XxxCell"</span> owner:<span class="literal">nil</span> options:<span class="literal">nil</span>] lastObject];</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="图片压缩"><a href="#图片压缩" class="headerlink" title="图片压缩"></a>图片压缩</h3><p>图片的压缩其实是两个概念
　　</p>
<ul>
<li>“压” 是指文件体积变小，但是像素数不变，长宽尺寸不变，那么质量可能下降；</li>
<li>“缩” 是指文件的尺寸变小，也就是像素数减少，而长宽尺寸变小，文件体积同样会减小。</li>
</ul>
<p>对图片只“压”不缩，有时候是达不到我们的需求的。比如图片已经被压得很模糊了但体积还是很大。因此，还要适当地“缩”图片。</p>
<h4 id="图片的“压”处理"><a href="#图片的“压”处理" class="headerlink" title="图片的“压”处理"></a>图片的“压”处理</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSData</span> *imgData = <span class="built_in">UIImageJPEGRepresentation</span>(image, <span class="number">0.5</span>);</div></pre></td></tr></table></figure>
<ul>
<li>第一个参数是图片对象。</li>
<li>第二个参数是压的系数，其值范围为0~1。<br>压的系数不宜太低，通常是0.3~0.7，过小则会很模糊，甚至可能会出现黑边等。<br>压的系数不等于压缩比例，需要慢慢调试到最佳。</li>
</ul>
<p>或者</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">NSData</span> *imgData = <span class="built_in">UIImagePNGRepresentation</span>(image);</div></pre></td></tr></table></figure>
<p>一般用 UIImagePNGRepresentation 返回的图片比 UIImageJPEGRepresentation 返回的图片更清晰，也就更大。使用 JPEG 的压处理比较可控。</p>
<h4 id="图片的“缩”处理"><a href="#图片的“缩”处理" class="headerlink" title="图片的“缩”处理"></a>图片的“缩”处理</h4><ul>
<li>给 UIImage 写一个分类，定义一个类方法来缩图片</li>
</ul>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/*</span></div><div class="line"> *  压缩图片至目标尺寸</div><div class="line"> *</div><div class="line"> *  @param sourceImage 源图片</div><div class="line"> *  @param targetWidth 图片最终尺寸的宽</div><div class="line"> *</div><div class="line"> *  @return 返回按照源图片的宽、高比例压缩至目标宽、高的图片</div><div class="line"> */</div><div class="line">+ (<span class="built_in">UIImage</span> *)compressImage:(<span class="built_in">UIImage</span> *)sourceImage toTargetWidth:(<span class="built_in">CGFloat</span>)targetWidth</div><div class="line">&#123;</div><div class="line">    <span class="built_in">CGSize</span> imageSize = sourceImage.size;</div><div class="line">    <span class="built_in">CGFloat</span> originWidth = imageSize.width;</div><div class="line">    <span class="built_in">CGFloat</span> originHeight = imageSize.height;</div><div class="line">    <span class="built_in">CGFloat</span> targetHeight = (targetWidth / originWidth) * originHeight;</div><div class="line">    </div><div class="line">    <span class="built_in">UIGraphicsBeginImageContextWithOptions</span>(<span class="built_in">CGSizeMake</span>(targetWidth, targetHeight), <span class="literal">NO</span>, <span class="number">0.0</span>);</div><div class="line">    [sourceImage drawInRect:<span class="built_in">CGRectMake</span>(<span class="number">0</span>, <span class="number">0</span>, targetWidth, targetHeight)];</div><div class="line">    <span class="built_in">UIImage</span> *scaledImage = <span class="built_in">UIGraphicsGetImageFromCurrentImageContext</span>();</div><div class="line">    <span class="built_in">UIGraphicsEndImageContext</span>();</div><div class="line">    </div><div class="line">    <span class="keyword">return</span> scaledImage;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>把“压”和“缩”都处理后，返回的NSData对象就可以上传到服务器了。</li>
</ul>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 源图片为upImage，指定压缩后的图片宽度为150，压缩系数为0.8</span></div><div class="line"><span class="built_in">NSData</span> *imageData = <span class="built_in">UIImageJPEGRepresentation</span>([<span class="built_in">UIImage</span> compressImage:upImage toTargetWidth:<span class="number">150</span>], <span class="number">0.8</span>);</div></pre></td></tr></table></figure>
<h3 id="动态计算cell高度"><a href="#动态计算cell高度" class="headerlink" title="动态计算cell高度"></a>动态计算cell高度</h3><p>动态计算cell的高度，一直贯穿了我的整个iOS开发，从入门的ISA，到正式项目的验房宝，一直到金锄头和一元领宝，下面进入详细报导。</p>
<hr>
<h2 id="动态计算cell高度-1"><a href="#动态计算cell高度-1" class="headerlink" title="动态计算cell高度"></a>动态计算cell高度</h2><p>假设现在有一个DKPersonCell，里面有一个模型DKPerson，要计算DKPerson模型的username(NSString)属性的文本高度。</p>
<h3 id="思路1-0-通过字数和字体大小计算文本的高度"><a href="#思路1-0-通过字数和字体大小计算文本的高度" class="headerlink" title="思路1.0 通过字数和字体大小计算文本的高度"></a>思路1.0 通过字数和字体大小计算文本的高度</h3><h4 id="给-NSString-写个分类，返回字符串的大小"><a href="#给-NSString-写个分类，返回字符串的大小" class="headerlink" title="给 NSString 写个分类，返回字符串的大小"></a>给 NSString 写个分类，返回字符串的大小</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * text:需要计算的文本 // @"bingo"</div><div class="line"> * maxSize: 限制大小 // CGSizeMake(MAXFLOAT, MAXFLOAT) 不限制</div><div class="line"> * fontSize: 字体大小 // 17</div><div class="line"> */</div><div class="line">+ (<span class="built_in">CGSize</span>)sizeWithText:(<span class="built_in">NSString</span> *)text maxSize:(<span class="built_in">CGSize</span>)maxSize fontSize:(<span class="built_in">CGFloat</span>)fontSize</div><div class="line">&#123;</div><div class="line">    <span class="built_in">CGSize</span> size = [text boundingRectWithSize:maxSize options:<span class="built_in">NSStringDrawingUsesLineFragmentOrigin</span> attributes:@&#123;<span class="built_in">NSFontAttributeName</span>:[<span class="built_in">UIFont</span> systemFontOfSize:fontSize]&#125; context:<span class="literal">nil</span>].size;</div><div class="line"></div><div class="line">    <span class="keyword">return</span> size;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="在cell的模型的setter方法中计算字符串的高度"><a href="#在cell的模型的setter方法中计算字符串的高度" class="headerlink" title="在cell的模型的setter方法中计算字符串的高度"></a>在cell的模型的setter方法中计算字符串的高度</h4><ul>
<li>在tableView的数据源方法cellForRowAtIndexPath:中给cell赋值一个模型对象</li>
</ul>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">- (<span class="built_in">UITableViewCell</span> *)tableView:(<span class="built_in">UITableView</span> *)tableView cellForRowAtIndexPath:(<span class="built_in">NSIndexPath</span> *)indexPath</div><div class="line">&#123;</div><div class="line">    DKPersonCell * cell = [DKPersonCell personCellWithTableView:tableView];</div><div class="line">    <span class="comment">// 给cell的模型对象赋值</span></div><div class="line">    cell.person = <span class="keyword">self</span>.persons[indexPath.row];</div><div class="line"></div><div class="line">    <span class="keyword">return</span> cell; </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>在 DKPersonCell.h 中定义一个 cellHeight 属性，用来保存cell的高度</li>
</ul>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/** cell的高度 */</span></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>,<span class="keyword">assign</span>) <span class="built_in">CGFloat</span> cellHeight;</div></pre></td></tr></table></figure>
<ul>
<li>在 DKPersonCell.m 中重写person的setter方法，计算文本高度</li>
</ul>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)setPerson:(DKPerson *)person</div><div class="line">&#123;</div><div class="line">    _person = person;</div><div class="line">    <span class="comment">// 参数1:要计算的文本</span></div><div class="line">    <span class="built_in">NSString</span> *text = person.username;</div><div class="line">    <span class="comment">// 参数2:设置最大限制大小</span></div><div class="line">    <span class="built_in">CGFloat</span> limitWidth = [<span class="built_in">UIScreen</span> mainScreen].bounds.size.width * <span class="number">0.7</span>;</div><div class="line">    <span class="built_in">CGFloat</span> limitHeight = MAXFLOAT;</div><div class="line">    <span class="built_in">CGSize</span> maxSize = <span class="built_in">CGSizeMake</span>(limitWidth, limitHeight);</div><div class="line">    <span class="comment">// 参数3:设置字体大小</span></div><div class="line">    <span class="built_in">CGFloat</span> fontSize = <span class="number">14.0</span>;</div><div class="line">    </div><div class="line">    <span class="comment">// 计算文本大小</span></div><div class="line">    <span class="built_in">CGSize</span> stringSize = [<span class="built_in">NSString</span> sizeWithText:text maxSize:maxSize fontSize:fontSize];</div><div class="line">    <span class="comment">// 文本的高度即为 stringSize.height</span></div><div class="line">    </div><div class="line">    <span class="comment">// 计算cell的高度</span></div><div class="line">    <span class="comment">// cell的高度要结合实际情况，这里举例的是纯文本情况</span></div><div class="line">    <span class="comment">// 如果是纯文本的cell，cell的高度就是文本的高度，或者再加上顶部和底部的间距;</span></div><div class="line">    <span class="comment">// 如果cell有其它控件，就要先计算高度固定部分的高度，然后再加上文本的高度;</span></div><div class="line">    <span class="keyword">self</span>.cellHeight = <span class="number">20</span> + stringSize.height;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="在控制器中定义个可变数组，用来保存模型的高度"><a href="#在控制器中定义个可变数组，用来保存模型的高度" class="headerlink" title="在控制器中定义个可变数组，用来保存模型的高度"></a>在控制器中定义个可变数组，用来保存模型的高度</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/** cell高度数组 */</span></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>,<span class="keyword">strong</span>) <span class="built_in">NSMutableArray</span> *cellHeightArr;</div></pre></td></tr></table></figure>
<h4 id="在-cellForRowAtIndexPath-中把模型的高度保存到高度数组中"><a href="#在-cellForRowAtIndexPath-中把模型的高度保存到高度数组中" class="headerlink" title="在 cellForRowAtIndexPath: 中把模型的高度保存到高度数组中"></a>在 cellForRowAtIndexPath: 中把模型的高度保存到高度数组中</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">- (<span class="built_in">UITableViewCell</span> *)tableView:(<span class="built_in">UITableView</span> *)tableView cellForRowAtIndexPath:(<span class="built_in">NSIndexPath</span> *)indexPath</div><div class="line">&#123;</div><div class="line">    DKPersonCell *cell = [DKPersonCell personCellWithTableView:tableView];</div><div class="line">    cell.person = <span class="keyword">self</span>.persons[indexPath.row];</div><div class="line">    <span class="comment">// 保存模型的高度到高度数组中</span></div><div class="line">    [<span class="keyword">self</span>.cellHeightArr addObject:@(cell.cellHeight)];</div><div class="line">    <span class="keyword">return</span> cell;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="在-heightForRowAtIndexPath-中返回对应模型的高度"><a href="#在-heightForRowAtIndexPath-中返回对应模型的高度" class="headerlink" title="在 heightForRowAtIndexPath: 中返回对应模型的高度"></a>在 heightForRowAtIndexPath: 中返回对应模型的高度</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (<span class="built_in">CGFloat</span>)tableView:(<span class="built_in">UITableView</span> *)tableView heightForRowAtIndexPath:(<span class="built_in">NSIndexPath</span> *)indexPath</div><div class="line">&#123;</div><div class="line">    <span class="keyword">if</span> (<span class="keyword">self</span>.cellHeightArr.count) &#123;</div><div class="line">        <span class="keyword">return</span> [<span class="keyword">self</span>.cellHeightArr[indexPath.row] doubleValue];</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="number">44</span>; <span class="comment">// 默认高度</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样就完成了动态计算cell高度的需求，但是这样是有风险的。</p>
<p>因为现在表格的数据源和代理各自对应了一个数组，这两个数组必须实时同步。</p>
<p>如果其中一个数组的元素增加或者减少了，而另外一个数组不变，一旦拽动表格程序就崩溃；如果两个数组在一个<code>run loop</code>周期内没有都更新完毕，程序立马崩溃，或者出现视图刷新时cell的高度不正确的情况。</p>
<p>另外，因为苹果显示文字的时候会有一个换行的算法，根据输入的字符串的类型去智能换行。</p>
<p>比如一行能显示10个汉字,当我输入了8个汉字再开始输入足够多的英文字母的时候，会发现英文的字符串被自动换行到下一行了，而第一行后边还剩下2个汉字的空白区域。那么可以想象如果这种情况出现得比较多，同样的字数和字体大小显示出来的行数要比理论计算得出来的更多。结合这种情况，计算字符串的高度也十分不稳定。</p>
<h3 id="思路2-0-获取UILabel显示的高度"><a href="#思路2-0-获取UILabel显示的高度" class="headerlink" title="思路2.0 获取UILabel显示的高度"></a>思路2.0 获取UILabel显示的高度</h3><p>思路1.0不足之处主要有两点：</p>
<ul>
<li>数据源和代理用了两个数组，会导致许多风险，不可控，应该只用一个数组。</li>
<li>计算字符串的高度是理论值，跟实际值有偏差。</li>
</ul>
<h4 id="在-xib-或者-storyboard-中把-UILabel-连线到-DKPerson-h"><a href="#在-xib-或者-storyboard-中把-UILabel-连线到-DKPerson-h" class="headerlink" title="在 xib 或者 storyboard 中把 UILabel 连线到 DKPerson.h"></a>在 xib 或者 storyboard 中把 UILabel 连线到 DKPerson.h</h4><ul>
<li>连的是需要显示文本的控件，可以是 UILabel、UITextView 等。</li>
<li>纯代码跳过连线，但要确保.h文件中有暴露控件。</li>
</ul>
<h4 id="在-DKPerson-h-中定义一个返回模型高度的对象方法，并在-DKPerson-m-中实现"><a href="#在-DKPerson-h-中定义一个返回模型高度的对象方法，并在-DKPerson-m-中实现" class="headerlink" title="在 DKPerson.h 中定义一个返回模型高度的对象方法，并在 DKPerson.m 中实现"></a>在 DKPerson.h 中定义一个返回模型高度的对象方法，并在 DKPerson.m 中实现</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/** 计算cell高度 */</span></div><div class="line">- (<span class="built_in">CGFloat</span>)cellHeight</div><div class="line">&#123;</div><div class="line">   <span class="comment">// 重新布局子控件</span></div><div class="line">   [<span class="keyword">self</span> layoutIfNeeded];</div><div class="line">   </div><div class="line">   <span class="comment">// 计算cell的高度</span></div><div class="line">   <span class="comment">// cell的高度仍然要结合实际情况，</span></div><div class="line">   <span class="comment">// 这里简单举例cell高度 = label的底部的y值 + label底部与cell底部的间距</span></div><div class="line">   <span class="built_in">CGFloat</span> cellHeight = <span class="built_in">CGRectGetMaxY</span>(<span class="keyword">self</span>.label.frame) + <span class="number">10</span>;</div><div class="line">   <span class="keyword">return</span> cellHeight;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="在控制器中定义一个DKPersonCell的工具对象，用来保存cell的高度"><a href="#在控制器中定义一个DKPersonCell的工具对象，用来保存cell的高度" class="headerlink" title="在控制器中定义一个DKPersonCell的工具对象，用来保存cell的高度"></a>在控制器中定义一个DKPersonCell的工具对象，用来保存cell的高度</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/** 计算cell高度的工具对象 */</span></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) DKPersonCell *personCellTool;</div></pre></td></tr></table></figure>
<h4 id="懒加载personCellTool"><a href="#懒加载personCellTool" class="headerlink" title="懒加载personCellTool"></a>懒加载personCellTool</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (DKPersonCell *)personCellTool</div><div class="line">&#123;</div><div class="line">    <span class="keyword">if</span> (!_personCellTool) &#123;</div><div class="line">         _personCellTool = [DKPersonCell personCellWithTableView:<span class="keyword">self</span>.tableView];</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> _chatCellTool;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="在-heightForRowAtIndexPath-方法中计算cell高度"><a href="#在-heightForRowAtIndexPath-方法中计算cell高度" class="headerlink" title="在 heightForRowAtIndexPath 方法中计算cell高度"></a>在 heightForRowAtIndexPath 方法中计算cell高度</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (<span class="built_in">CGFloat</span>)tableView:(<span class="built_in">UITableView</span> *)tableView heightForRowAtIndexPath:(<span class="built_in">NSIndexPath</span> *)indexPath</div><div class="line">&#123;</div><div class="line">    <span class="comment">// 给计算cell高度的工具对象赋值模型</span></div><div class="line">    <span class="keyword">self</span>.personCellTool.person = <span class="keyword">self</span>.persons[indexPath.row];</div><div class="line">    <span class="comment">// 计算cell高度</span></div><div class="line">    <span class="keyword">return</span> [<span class="keyword">self</span>.personCellTool cellHeight];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样就可以完美的实现动态计算cell的高度了~</p>
<p>如果您没有成功，请仔细检查代码，并确定label有设置多行显示，还要约束控件的宽度或者设置explicit来限制单行最长长度。</p>
<h3 id="其它情景"><a href="#其它情景" class="headerlink" title="其它情景"></a>其它情景</h3><p>上面演示的是简单地计算与NSString相关的控件高度，实际开发中可能会遇到别的情况。</p>
<p>比如验房宝中的cell要根据房间数来决定，要计算一行能放多少间房，然后计算一共要放多少行，然后再计算总的房间高度，以此来得出cell的高度。</p>
<p>但2.0思路都是通用的:</p>
<ul>
<li>cell暴露一个返回cell高度的方法;</li>
<li>在控制器中懒加载一个计算cell高度的工具对象(cell);</li>
<li>在表格的 heightForRowAtIndexPath 给工具对象set一下对应row的模型，然后调用cell返回高度的方法来得到cell的高度。</li>
</ul>
<p>唯一不同的就是cell中返回高度的方法实现，具体情况具体分析。</p>
<hr>
<h2 id="开发中用到的第三方框架"><a href="#开发中用到的第三方框架" class="headerlink" title="开发中用到的第三方框架"></a>开发中用到的第三方框架</h2><ul>
<li>网络请求 : AFNetworking</li>
<li>上拉/下拉刷新 : MJRefresh</li>
<li>字典转模型 : MJExtension</li>
<li>图片浏览器 : MJPhotoBrowser</li>
<li>图片加载 : SDWebImage</li>
<li>HUD : SVProgressHUD、MBProgressHUD</li>
<li>数据缓存归档 : YYCache</li>
<li>第三方支付 : Ping++、BeeCloud、Iapppay</li>
<li>第三方登录 : Mob</li>
<li>社交分享 : Mob</li>
<li>键盘处理 : IQKeyboardManager</li>
<li>即时聊天 : EaseMob</li>
<li>录音 : EMCDDeviceManager</li>
</ul>
<h3 id="第三方框架的坑"><a href="#第三方框架的坑" class="headerlink" title="第三方框架的坑"></a>第三方框架的坑</h3><h4 id="AFNetworking"><a href="#AFNetworking" class="headerlink" title="AFNetworking"></a>AFNetworking</h4><p>很常见的一个坑：解析 text/html 格式失败</p>
<p>需要在 AFURLResponseSerialization.m 文件的 init 方法的 acceptableContentTypes 中添加@”text/html”</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">instancetype</span>)init &#123;</div><div class="line">    <span class="keyword">self</span> = [<span class="keyword">super</span> init];</div><div class="line">    <span class="keyword">if</span> (!<span class="keyword">self</span>) &#123;</div><div class="line">        <span class="keyword">return</span> <span class="literal">nil</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">self</span>.acceptableContentTypes = [<span class="built_in">NSSet</span> setWithObjects: <span class="string">@"application/json"</span>, <span class="string">@"text/json"</span>, <span class="string">@"text/javascript"</span>, <span class="string">@"text/html"</span>, <span class="literal">nil</span>];</div><div class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="IQKeyboardManager"><a href="#IQKeyboardManager" class="headerlink" title="IQKeyboardManager"></a>IQKeyboardManager</h4><p>有导航栏控制器的时候，点击输入框进入编辑状态弹出键盘，导航栏会被顶上去挤出界面。需要在 IQUIView+Hierarchy.m 文件中的 topMostController 方法中，把以下代码段注释掉。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//    while (matchController != nil &amp;&amp; [controllersHierarchy containsObject:matchController] == NO)</span></div><div class="line"><span class="comment">//    &#123;</span></div><div class="line"><span class="comment">//        do</span></div><div class="line"><span class="comment">//        &#123;</span></div><div class="line"><span class="comment">//            matchController = [matchController nextResponder];</span></div><div class="line"><span class="comment">//            </span></div><div class="line"><span class="comment">//        &#125; while (matchController != nil &amp;&amp; [matchController isKindOfClass:[UIViewController class]] == NO);</span></div><div class="line"><span class="comment">//    &#125;</span></div></pre></td></tr></table></figure>
<p>如果做了以上修改，可能会有一个 bug，就是 push 后马上给输入框获取焦点，收起键盘后会发现 self.view 向上偏移了64个点，也就是导航栏的高度。</p>
<p>原理是如果不注释这段代码，那么该方法返回的是导航栏控制器，IQKeyBoardManager 会将导航栏控制器的view一起偏移，注释掉后返回的就是 viewController 而不是 NavigationViewController，就不会把导航栏移上去了。</p>
<p>如果真的有刚需进入控制器就进入编辑状态，并且出现了上述的 view 上移的 bug，那 becomeFirstResponder 就不要写在 viewDidLoad 里，应该写在 viewDidAppear 里。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Bingo
    </li>
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://bingozb.github.io/3.html" title="iOS战斗总结笔记一期">https://bingozb.github.io/3.html</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 MIT 许可协议。转载请注明出处！
    </li>
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/1.html" rel="next" title="MySQL支持emoji字符的插入">
                <i class="fa fa-chevron-left"></i> MySQL支持emoji字符的插入
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Bingo" />
          <p class="site-author-name" itemprop="name">Bingo</p>
           
              <p class="site-description motion-element" itemprop="description">He who hesitates is lost.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bingozb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/bingozb" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/bingo_v587" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/profile.php?id=100013406670597" target="_blank" title="Facebook">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  Facebook
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#笔记"><span class="nav-number">1.</span> <span class="nav-text">笔记</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#分类中定义的属性名最好添加一个前缀"><span class="nav-number">1.1.</span> <span class="nav-text">分类中定义的属性名最好添加一个前缀</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#导航栏标题"><span class="nav-number">1.2.</span> <span class="nav-text">导航栏标题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#宏"><span class="nav-number">1.3.</span> <span class="nav-text">宏</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Nib文字换行"><span class="nav-number">1.4.</span> <span class="nav-text">Nib文字换行</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AutoLayout"><span class="nav-number">1.5.</span> <span class="nav-text">AutoLayout</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IBOutlet"><span class="nav-number">1.6.</span> <span class="nav-text">IBOutlet</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#weak-amp-strong"><span class="nav-number">1.7.</span> <span class="nav-text">weak & strong</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#dispatch-async"><span class="nav-number">1.8.</span> <span class="nav-text">dispatch_async</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#方法一"><span class="nav-number">1.8.1.</span> <span class="nav-text">方法一</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#方法二"><span class="nav-number">1.8.2.</span> <span class="nav-text">方法二</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#UICollectionView加载不到xib"><span class="nav-number">1.9.</span> <span class="nav-text">UICollectionView加载不到xib</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#图片压缩"><span class="nav-number">1.10.</span> <span class="nav-text">图片压缩</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#图片的“压”处理"><span class="nav-number">1.10.1.</span> <span class="nav-text">图片的“压”处理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#图片的“缩”处理"><span class="nav-number">1.10.2.</span> <span class="nav-text">图片的“缩”处理</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#动态计算cell高度"><span class="nav-number">1.11.</span> <span class="nav-text">动态计算cell高度</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#动态计算cell高度-1"><span class="nav-number">2.</span> <span class="nav-text">动态计算cell高度</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#思路1-0-通过字数和字体大小计算文本的高度"><span class="nav-number">2.1.</span> <span class="nav-text">思路1.0 通过字数和字体大小计算文本的高度</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#给-NSString-写个分类，返回字符串的大小"><span class="nav-number">2.1.1.</span> <span class="nav-text">给 NSString 写个分类，返回字符串的大小</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在cell的模型的setter方法中计算字符串的高度"><span class="nav-number">2.1.2.</span> <span class="nav-text">在cell的模型的setter方法中计算字符串的高度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在控制器中定义个可变数组，用来保存模型的高度"><span class="nav-number">2.1.3.</span> <span class="nav-text">在控制器中定义个可变数组，用来保存模型的高度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在-cellForRowAtIndexPath-中把模型的高度保存到高度数组中"><span class="nav-number">2.1.4.</span> <span class="nav-text">在 cellForRowAtIndexPath: 中把模型的高度保存到高度数组中</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在-heightForRowAtIndexPath-中返回对应模型的高度"><span class="nav-number">2.1.5.</span> <span class="nav-text">在 heightForRowAtIndexPath: 中返回对应模型的高度</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#思路2-0-获取UILabel显示的高度"><span class="nav-number">2.2.</span> <span class="nav-text">思路2.0 获取UILabel显示的高度</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#在-xib-或者-storyboard-中把-UILabel-连线到-DKPerson-h"><span class="nav-number">2.2.1.</span> <span class="nav-text">在 xib 或者 storyboard 中把 UILabel 连线到 DKPerson.h</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在-DKPerson-h-中定义一个返回模型高度的对象方法，并在-DKPerson-m-中实现"><span class="nav-number">2.2.2.</span> <span class="nav-text">在 DKPerson.h 中定义一个返回模型高度的对象方法，并在 DKPerson.m 中实现</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在控制器中定义一个DKPersonCell的工具对象，用来保存cell的高度"><span class="nav-number">2.2.3.</span> <span class="nav-text">在控制器中定义一个DKPersonCell的工具对象，用来保存cell的高度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#懒加载personCellTool"><span class="nav-number">2.2.4.</span> <span class="nav-text">懒加载personCellTool</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在-heightForRowAtIndexPath-方法中计算cell高度"><span class="nav-number">2.2.5.</span> <span class="nav-text">在 heightForRowAtIndexPath 方法中计算cell高度</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其它情景"><span class="nav-number">2.3.</span> <span class="nav-text">其它情景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开发中用到的第三方框架"><span class="nav-number">3.</span> <span class="nav-text">开发中用到的第三方框架</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#第三方框架的坑"><span class="nav-number">3.1.</span> <span class="nav-text">第三方框架的坑</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#AFNetworking"><span class="nav-number">3.1.1.</span> <span class="nav-text">AFNetworking</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#IQKeyboardManager"><span class="nav-number">3.1.2.</span> <span class="nav-text">IQKeyboardManager</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  Copyright © 
  <span itemprop="copyrightYear">2017
  </span>
  <span class="author" itemprop="copyrightHolder">Bingo
  </span>
  All rights reserved.
</div>
        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcdzpa3';
      var conf = 'c0c6117021d1cea9f11629100efd8446';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      $('#local-search-input').focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("A9MeTkIR49W9kOOSvkggsXge-gzGzoHsz", "HaIEOSDyxpcjwOjRjCYxiWjA");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
